package logic

import (
	"context"
	"errors"
	"fresh-box/freshrpc/freshrpc"
	"fresh-box/freshrpc/internal/svc"
	"fresh-box/models/mysql"
	"github.com/zeromicro/go-zero/core/logx"
)

type FreshAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshAddLogic {
	return &FreshAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FreshAddLogic) FreshAdd(in *freshrpc.FreshAddRequest) (*freshrpc.FreshAddResponse, error) {
	// todo: add your logic here and delete this line

	var findFresh mysql.Fresh
	begin := mysql.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			begin.Rollback()
		}
	}()
	//查询商品是否存在
	err := findFresh.FindFreshByFreshName(begin, in.FreshName)
	if err == nil {
		begin.Rollback()
		return nil, errors.New("商品已存在")
	}

	var goods_type mysql.GoodsType
	//商品类型是否存在不存在则创建
	err = goods_type.FindGoodsTypeByName(begin, in.TypeName)
	if err != nil {
		goods_type = mysql.GoodsType{
			Name: in.TypeName,
		}
		err = goods_type.GoodsTypeAdd(begin)
		if err != nil {
			begin.Rollback()
			return nil, errors.New("添加分类失败")
		}
	}

	fresh := &mysql.Fresh{
		Tid:          int(goods_type.ID),
		FreshName:    in.FreshName,
		FreshContent: in.FreshContent,
		FreshPrice:   float64(in.FreshPrice),
	}
	err = fresh.FreshAdd(begin)
	if err != nil {
		begin.Rollback()
		return nil, err
	}
	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		return nil, err
	}
	return &freshrpc.FreshAddResponse{
		FreshId: int64(fresh.ID),
	}, nil
}
